//
//  RNIOSExportJsToReact.m
//  xmgjAppFront
//
//  Created by 汪滔 on 2020/7/1.
//

#import <Foundation/Foundation.h>
#import "DataModule.h"
#import <React/RCTLog.h>
#import <ZLPhotoBrowser/ZLPhotoBrowser.h>

#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>

#define PHOTOCACHEPATH [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
#define VIDEOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"videoCache"]

@implementation DataModule

RCTResponseSenderBlock photoPickerCallBackBlock;
RCTResponseSenderBlock photoPickerNewCallBackBlock;
RCTResponseSenderBlock imageOrVideoCallBackBlock;
RCTResponseSenderBlock getAllWaterBlock;

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(sendRnPageCompleted){
  
}
RCT_EXPORT_METHOD(getCommonData:(NSString *)key callback:(RCTResponseSenderBlock) callback){
  
}
RCT_EXPORT_METHOD(chooseImage:(RCTResponseSenderBlock) callback){
  photoPickerNewCallBackBlock = callback;
  [self new_showPhotoPickerWith:1];
}


RCT_EXPORT_METHOD(chooseImageOrVideo:(RCTResponseSenderBlock) callback){
  imageOrVideoCallBackBlock = callback;
  [self new_showPhotoPickerWith:2];
}



RCT_EXPORT_METHOD(chooseImageIos:(NSString *)type callback:(RCTResponseSenderBlock) callBack){
  photoPickerCallBackBlock = callBack;
  NSString *urlString = [GJImageUpdateURl stringByAppendingString:type];
  [self showPhotoPicker:urlString];
}
RCT_EXPORT_METHOD(checkVersion:(NSString *)type){
  dispatch_async(dispatch_get_main_queue(), ^{
    //查询版本
    if ([type isEqualToString:@"initlization"]) {
      [GJUtil checkVersion:^(BOOL showToast) {
        
      }];
    }else{
      [GJUtil checkVersion:^(BOOL showToast) {
        [MBProgressHUD cr_showToastWithView:[UIApplication sharedApplication].keyWindow.rootViewController.view text:@"已是最新版本"];
      }];
    }
    
  });
}


- (instancetype)init
{
  self = [super init];
  if (self) {
    
  }
  return self;
}


- (void)new_showPhotoPickerWith:(NSInteger)type{
  dispatch_async(dispatch_get_main_queue(), ^{
    ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
    
    // 相册参数配置，configuration有默认值，可直接使用并对其属性进行修改
    ac.configuration.maxSelectCount = 1;
    ac.configuration.maxPreviewCount = 1;
    ac.configuration.allowTakePhotoInLibrary = YES;
    
    if (type==1) {
      ac.configuration.allowSelectVideo = NO;
    }
    //如调用的方法无sender参数，则该参数必传
    ac.sender = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 选择回调
    [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
      
      if (assets.count > 0) {
        PHAsset * asset = assets.firstObject;
        switch (asset.mediaType) {
          case 1:
          {
            //图片
            NSString *filePath = @"/gj_imageCache.jpeg";
            NSData *data = UIImageJPEGRepresentation(images[0], 0.5f);
            if ([self saveImage:data toCachePath:filePath]) {
              NSString *encodedImageStr = [data base64EncodedStringWithOptions:0];
              if (imageOrVideoCallBackBlock) {
                imageOrVideoCallBackBlock(@[[PHOTOCACHEPATH stringByAppendingString:filePath],encodedImageStr,@"image", [filePath pathExtension]]);
              }
              if (photoPickerNewCallBackBlock) {
                photoPickerNewCallBackBlock(@[[PHOTOCACHEPATH stringByAppendingString:filePath],encodedImageStr]);
              }
              
              
            }else{
              
            }
          }
            break;
          case 2:
          {
            //视频
            NSString *filePath = [NSString stringWithFormat:@"/var/mobile/Media/%@/%@",[asset valueForKey:@"_directory"],[asset valueForKey:@"_filename"]];
            NSURL *url = [[NSURL alloc]initFileURLWithPath:filePath];
            UIImage *firstImage = [self getVideoPreViewImageWithPath:url];
            NSData *data = UIImageJPEGRepresentation(firstImage, 0.5f);
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
            if (![[filePath pathExtension] isEqualToString:@"MOV"] && ![[filePath pathExtension] isEqualToString:@"mov"])  {
              if (imageOrVideoCallBackBlock) {
                imageOrVideoCallBackBlock(@[filePath,encodedImageStr,@"video",[filePath pathExtension]]);
              }
            }else{
              [self mov2mp4:url encodedImageStr:encodedImageStr];
            }
            
            
          }
            break;
          default:
            break;
        }
      }
      
      
      
      
    }];
    
    // 调用相册
    //    [ac showPreviewAnimated:YES];
    [ac showPhotoLibrary];
  });
}

/// 图片选择
- (void)showPhotoPicker:(NSString *)urlString{
  dispatch_async(dispatch_get_main_queue(), ^{
    ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
    
    // 相册参数配置，configuration有默认值，可直接使用并对其属性进行修改
    ac.configuration.maxSelectCount = 1;
    ac.configuration.maxPreviewCount = 1;
    
    //如调用的方法无sender参数，则该参数必传
    ac.sender = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 选择回调
    [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
      //your codes
      if (images.count > 0) {
        NSData *data = UIImageJPEGRepresentation(images[0], 0.5f);
        //        NSData *data = UIImagePNGRepresentation(images.firstObject);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        //        PHAsset *asset = assets.firstObject;
        //        NSString *filePath = [NSString stringWithFormat:@"/var/mobile/Media/%@/%@",[asset valueForKey:@"_directory"],[asset valueForKey:@"_filename"]];
        
        [self uploadImagefile:data base64String:encodedImageStr urlSting:urlString];
        //        photoPickerCallBackBlock(@[[filePath gj_hasValue]?filePath:@"",encodedImageStr]);
      }
    }];
    
    // 调用相册
    //    [ac showPreviewAnimated:YES];
    [ac showPhotoLibrary];
  });
}




//获取视频的第一帧截图, 返回UIImage
//需要导入AVFoundation.h
- (UIImage*) getVideoPreViewImageWithPath:(NSURL *)videoPath
{
  AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];
  
  AVAssetImageGenerator *gen         = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  gen.appliesPreferredTrackTransform = YES;
  
  CMTime time      = CMTimeMakeWithSeconds(0.0, 600);
  NSError *error   = nil;
  
  CMTime actualTime;
  CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
  UIImage *img     = [[UIImage alloc] initWithCGImage:image];
  
  return img;
}


//将Image保存到缓存路径中
- (BOOL)saveImage:(NSData *)imageData toCachePath:(NSString *)path {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *fullPath = [PHOTOCACHEPATH stringByAppendingString:path];
  if (![fileManager fileExistsAtPath:fullPath]) {
    [fileManager createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent]
           withIntermediateDirectories:YES
                            attributes:nil
                                 error:nil];
  } else {
    if ([fileManager removeItemAtPath:path error:nil]) {
      [fileManager createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent]
             withIntermediateDirectories:YES
                              attributes:nil
                                   error:nil];
    }
    
  }
  NSError *error;
  //    if ([imageData writeToFile:fullPath options:0 error:&error]) {
  //
  //    }else{
  //      NSLog(@"writeToFile failed with error %@", error);
  //    }
  //  return NO;
  //  return [data writeToFile:fullPath atomically:YES];
  return [imageData writeToFile:fullPath options:0 error:&error];
}



//以当前时间合成图片名称
- (NSString *)getImageNameBaseCurrentTime {
  
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
  
  return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".jpeg"];
}

//以当前时间合成视频名称
- (NSString *)getVideoNameBaseCurrentTime {
  
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
  
  return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".MOV"];
}





/// 上传图片到服务器
/// @param file imageData
/// @param base64String base64String description
- (void)uploadImagefile:(NSData *)file base64String:(NSString *)base64String urlSting:(NSString *)urlString{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:[UIApplication sharedApplication].keyWindow.rootViewController.view text:@""];
  NSDictionary *params = @{
  };
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                       
                                                       @"text/html",
                                                       
                                                       @"image/jpeg",
                                                       
                                                       @"image/png",
                                                       
                                                       @"application/octet-stream",
                                                       
                                                       @"text/json",
                                                       
                                                       nil];
  
  [manager.requestSerializer setValue:@"multipart/form-data;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  
  
  [manager POST:urlString parameters:params  headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    
    //给定数据流的数据名，文件名，文件类型（以图片为例）
    [formData appendPartWithFileData:file name:@"file" fileName:@"image.jpeg" mimeType:@"image/jpeg"];
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    [hud cr_hide];
    NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *dataDic = resDict[@"data"];
    
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic && dataDic.count > 0) {
      //      NSDictionary *dataDic = resDict[@"data"];
      //      if (dataDic) {
      NSString *urlString  =  dataDic[@"url"] ? dataDic[@"url"] : @"";
      photoPickerCallBackBlock(@[@{@"code":resDict[@"code"],@"msg":resDict[@"msg"]},urlString,base64String]);
      //      }
    }else{
      photoPickerCallBackBlock(@[@{@"code":resDict[@"code"],@"msg":resDict[@"msg"]},[NSNull null],[NSNull null]]);
    }
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    photoPickerCallBackBlock(@[@{@"code":@(error.code),@"msg":@"网络连接失败"},[NSNull null],[NSNull null]]);
    [hud cr_hide];
  }];
  
  
}

/// 转换视频格式
/// @param movUrl 视频地址
/// @param encodedImageStr 视频封面图片
- (void)mov2mp4:(NSURL *)movUrl encodedImageStr:(NSString *)encodedImageStr
{
  AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
  NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
  /**
   AVAssetExportPresetMediumQuality 表示视频的转换质量，
   */
  if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    
    //转换完成保存的文件路径
    NSString * resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4",@"cvt"];
    
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if(![fm fileExistsAtPath:resultPath]){
      [fm createDirectoryAtPath:resultPath
    withIntermediateDirectories:YES
                     attributes:nil
                          error:nil];
    }else{
      [fm removeItemAtPath:resultPath error:nil];
    }
    
    exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
    
    //要转换的格式，这里使用 MP4
    exportSession.outputFileType = AVFileTypeMPEG4;
    
    //转换的数据是否对网络使用优化
    exportSession.shouldOptimizeForNetworkUse = YES;
    
    //异步处理开始转换
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     
     {
      //转换状态监控
      switch (exportSession.status) {
        case AVAssetExportSessionStatusUnknown:
          GJLog(@"AVAssetExportSessionStatusUnknown");
          break;
          
        case AVAssetExportSessionStatusWaiting:
          GJLog(@"AVAssetExportSessionStatusWaiting");
          break;
          
        case AVAssetExportSessionStatusExporting:
          GJLog(@"AVAssetExportSessionStatusExporting");
          break;
        case AVAssetExportSessionStatusFailed:
          GJLog(@"AVAssetExportSessionStatusFailed");
          break;
        case AVAssetExportSessionStatusCancelled:
          GJLog(@"AVAssetExportSessionStatusCancelled");
          break;
          
        case AVAssetExportSessionStatusCompleted:
        {
          //转换完成
          GJLog(@"AVAssetExportSessionStatusCompleted");
          imageOrVideoCallBackBlock(@[resultPath,encodedImageStr,@"video",[resultPath pathExtension]]);
          break;
        }
      }
      
    }];
    
  }
}

- (NSString*)dataPath
{
  NSString *dataPath = [NSString stringWithFormat:@"%@/Library/appdata/chatbuffer", NSHomeDirectory()];
  NSFileManager *fm = [NSFileManager defaultManager];
  if(![fm fileExistsAtPath:dataPath]){
    [fm createDirectoryAtPath:dataPath
  withIntermediateDirectories:YES
                   attributes:nil
                        error:nil];
  }
  return dataPath;
}
#pragma mark -- 水印相机
RCT_EXPORT_METHOD(getAllWater:(RCTResponseSenderBlock) callBack){
  dispatch_async(dispatch_get_main_queue(), ^{
    NSString *filePath =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]  stringByAppendingPathComponent:@"waterPhotoDic.plist"];
    NSDictionary *localDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    if (localDic && localDic.count > 0 ) {
      NSString *fullPath =  [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"waterPhotos"];
      NSMutableDictionary *backDic = [NSMutableDictionary dictionary];
      [localDic enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSDictionary * obj, BOOL * _Nonnull stop) {
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:obj];
        [tempDic setObject:[fullPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg",obj[@"imageId"]]] forKey:@"filePath"];
        [backDic setObject:tempDic forKey:obj[@"imageId"]];
      }];
      NSArray *callBackArray = [backDic allValues];
      callBack(@[[callBackArray jsonPrettyStringEncoded]]);
    }else{
      callBack(@[[@[] jsonPrettyStringEncoded]]);
    }
    
  });
}
RCT_EXPORT_METHOD(saveWaterInfo:(NSString *) jsonString){
  dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary *dictioary = [jsonString jsonValueDecoded];
    NSString *filePath =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]  stringByAppendingPathComponent:@"waterPhotoDic.plist"];
    NSMutableDictionary *localDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    if (!localDic) {
      //模型：
      NSDictionary *saveDic = @{dictioary[@"imageId"]: dictioary};

      BOOL success = [saveDic writeToFile:filePath atomically:YES];
      if (success) {
        GJLog(@"zeki保存成功")
      }else{
        GJLog(@"zeki保存失败")
      }
    }else{
      if (!localDic[dictioary[@"imageId"]]) {
        [localDic setObject:dictioary forKey:dictioary[@"imageId"]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSError *error = nil;
        if ([fileManager fileExistsAtPath:filePath]) {
          [fileManager removeItemAtPath:filePath error:&error];
        }
        
        BOOL success = [localDic writeToFile:filePath atomically:YES];
        if (success) {
          GJLog(@"zeki保存成功")
        }else{
          GJLog(@"zeki保存失败")
        }
      }
    }
    
  });
  
}
RCT_EXPORT_METHOD(uploadWaterSuccess:(NSString *) backjson){
  dispatch_async(dispatch_get_main_queue(), ^{
    NSString *filePath =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]  stringByAppendingPathComponent:@"waterPhotoDic.plist"];
    NSMutableDictionary *localDic = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath];
    id backData = [backjson jsonValueDecoded];
    if ([backData isKindOfClass:[NSArray class]]) {
      NSArray *dataArray = [[NSArray alloc]initWithArray:(NSArray *)backData];
      if (dataArray && dataArray.count > 0) {
        for (id dic  in dataArray) {
          if ([dic isKindOfClass:[NSDictionary class]]) {
            NSString *imageId = dic[@"imageId"];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *fullPath = dic[@"filePath"];
            NSError *error = nil;
            if ([fileManager fileExistsAtPath:fullPath]) {
              [fileManager removeItemAtPath:fullPath error:&error];
            }
            if (localDic && localDic[imageId]) {
              [localDic removeObjectForKey:imageId];
            }
          }
        }
        // 更新存储
        [localDic writeToFile:filePath atomically:YES];
      }
    }else{
      NSDictionary *dic = (NSDictionary *)backData;
      NSString *imageId = dic[@"imageId"];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSString *fullPath = dic[@"filePath"];
      NSError *error = nil;
      if ([fileManager fileExistsAtPath:fullPath]) {
        [fileManager removeItemAtPath:fullPath error:&error];
      }
      if (localDic && localDic[imageId]) {
        [localDic removeObjectForKey:imageId];
        // 更新存储
        [localDic writeToFile:filePath atomically:YES];
      }
    }
    
  });
}
@end
